<template>
  <div style="padding: 10px">
    <el-form class="form-container" ref="elForm" size="medium" :inline="true">
      <el-form-item label="日期">
        <el-row>
          <DatePicker
            ref="DatePicker"
            @changeDateTime="changeTime"
          ></DatePicker>
        </el-row>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input
          v-model="queryForm.productName"
          placeholder="请输入产品名称"
          clearable
          style="width: 160px"
          size="mini"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="searchWorkOrder"
          >查询
        </el-button>
        <el-button
          size="mini"
          type="success"
          icon="el-icon-refresh-right"
          @click="reset"
          >重置
        </el-button>
        <el-button
          size="mini"
          type="danger"
          icon="el-icon-download"
          @click="exportExcel"
          >导出表格
        </el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border stripe>
      <el-table-column
        label="序号"
        type="index"
        :index="1"
        align="center"
      ></el-table-column>
      <el-table-column
        label="工单编号"
        prop="wrokId"
        align="center"
      ></el-table-column>
      <el-table-column
        label="发布时间"
        width="160"
        prop="workAddTime"
        align="center"
      ></el-table-column>
      <el-table-column
        label="产品名称"
        prop="productName"
        align="center"
      ></el-table-column>
      <el-table-column
        label="数量"
        prop="wrokNum"
        align="center"
      ></el-table-column>
      <el-table-column
        label="单位"
        prop="unit"
        align="center"
      ></el-table-column>
      <el-table-column label="状态" prop="proStatus" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.proStatus == 1">生产中</el-tag>
          <el-tag v-else type="success">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        prop="workRemark"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" prop="" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="editWorkOrder(scope.row)"
            >编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="delWorkOrder(scope.row)"
            >删除
          </el-button>
          <el-button
            type="text"
            size="small"
            :disabled="scope.row.proStatus == 2"
            icon="el-icon-check"
            @click="endWorkOrder(scope.row)"
            >结束
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑" :visible.sync="editDialog" center>
      <el-card v-show="showSkeleton">
        <el-skeleton :rows="1" animated>
          <template slot="template">
            <el-row :gutter="10">
              <el-col :span="3" v-for="(item, index) in 8" :key="index">
                <el-skeleton-item
                  variant="button"
                  style="width: 100%; height: 40px; border-radius: 0 !important"
                ></el-skeleton-item>
              </el-col>
              <el-col :span="3">
                <el-skeleton-item
                  variant="h3"
                  style="width: 100%; margin: 25px 0 8px 0"
                ></el-skeleton-item>
              </el-col>
              <el-col :span="21">
                <el-skeleton-item
                  variant="button"
                  style="width: 100%; margin: 15px 0 8px 0"
                ></el-skeleton-item>
              </el-col>
              <el-col :span="3">
                <el-skeleton-item
                  variant="h3"
                  style="width: 100%; margin: 25px 0 8px 0"
                ></el-skeleton-item>
              </el-col>
              <el-col :span="21">
                <el-skeleton-item
                  variant="button"
                  style="width: 100%; margin: 15px 0 8px 0"
                ></el-skeleton-item>
              </el-col>
            </el-row>
          </template>
        </el-skeleton>
      </el-card>

      <el-tabs v-show="!showSkeleton" type="border-card" tab-position="top">
        <el-tab-pane
          v-for="item in proWorkAllVo.proWorkCrafts"
          :key="item.pkCraftInfo"
          :label="item.craftOrder + ' - ' + item.craftName"
        >
          <el-form label-position="right" label-width="100px">
            <el-form-item label="已参与员工">
              <el-select
                disabled
                v-model="item.userIds"
                placeholder=""
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="user in staffList"
                  :key="String(user.userId)"
                  :label="user.nickName"
                  :value="String(user.userId)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="新参与员工">
              <el-select
                v-model="item.newUserIds"
                placeholder="请选择新参与员工"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="user in item.allUserList"
                  :key="String(user.userId)"
                  :label="user.nickName"
                  :value="String(user.userId)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>
    <el-pagination
      style="margin-top: 10px"
      align="center"
      :hide-on-single-page="false"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 15, 20, 30]"
      :page-size="10"
      :current-page="queryForm.pageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
  </div>
</template>

<script>
const moment = require("moment");
import {
  addWorkOrder,
  delWorkOrder,
  endWorkOrder,
  getHistoryWorkOrder,
  getWorkOrderDetail,
} from "@/api/workOrder/workOrder";
import { getAllListUserApi } from "@/api/salary/salary";
import DatePicker from "@/components/DatePicker/index";
export default {
  components: {
    DatePicker,
  },
  data() {
    return {
      queryForm: {
        addStatus: "1", // 发布状态 0未发布 1已发布
        startTime: "", // 开始时间
        endTime: "", // 结束时间
        productName: "", // 产品名称
        pageNum: 1, // 当前页
        pageSize: 10, // 每页最大数
      },
      tableData: [],
      total: null,
      staffList: [],
      showSkeleton: true,
      editDialog: false,
      proWorkAllVo: {
        productName: "", // 产品名称
        pkProProduct: "", // 产品主键
        unit: "", // 单位
        workAddTime: "", // 工单发布时间
        workRemark: "", // 备注
        wrokId: "", // 工单编号
        wrokNum: null, // 数量
        addStatus: 0, // 发布状态 0未发布 1已发布
        pkProWork: "", // 工单主键
        proStatus: 1, // 生产状态 1.生产中 2已完成
        proWorkCrafts: [], // 功序列表
      },
    };
  },
  created() {
    this.initDate();
    this.getAllStaffList();
    this.getHistoryWorkOrderList();
  },
  methods: {
    initDate() {
      // 获取当月第一天
      const firstDayOfMonth = moment()
        .startOf("month")
        .format("YYYY-MM-DD HH:mm:ss");
      // 获取当月最后一天
      const lastDayOfMonth = moment()
        .endOf("month")
        .format("YYYY-MM-DD HH:mm:ss");
      this.queryForm.startTime = firstDayOfMonth;
      this.queryForm.endTime = lastDayOfMonth;
      this.$nextTick(() => {
        this.$refs.DatePicker.startTime = firstDayOfMonth;
        this.$refs.DatePicker.endTime = lastDayOfMonth;
      });
    },
    // 选择日期
    changeTime(e) {
      this.queryForm.startTime = moment(e.startTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      // 设置 endTime 为 e.endTime 日期的 23:59:59
      let endTimeMoment = moment(e.endTime); // 确保 e.endTime 是 moment 对象
      endTimeMoment.hours(23).minutes(59).seconds(59); // 设置时间为 23:59:59
      this.queryForm.endTime = endTimeMoment.format("YYYY-MM-DD HH:mm:ss"); // 格式化 endTime
      this.queryForm.pageNum = 1;
    },

    // 获取所有员工列表
    async getAllStaffList() {
      const res = await getAllListUserApi();
      this.staffList = res;
      // console.log(this.staffList)
    },
    // 获取历史工单列表
    async getHistoryWorkOrderList() {
      let res = await getHistoryWorkOrder(this.queryForm);
      // console.log(res);
      this.tableData = res.data.list;
      this.total = res.data.total;
    },
    // 查询
    searchWorkOrder() {
      if (
        (this.queryForm.startTime && this.queryForm.endTime) ||
        this.queryForm.productName
      ) {
        this.getHistoryWorkOrderList(this.queryForm);
      } else {
        this.$message.info("请至少填写一种筛选条件");
        return false;
      }
    },
    // 重置
    reset() {
      this.queryForm.startTime = "";
      this.queryForm.endTime = "";
      this.queryForm.productName = "";
    },
    // 导出表格
    async exportExcel() {
      this.download(
        "/business/work/export",
        {
          ...this.queryForm,
        },
        `工单${new Date().getTime()}.xlsx`
      );
    },
    //编辑工单
    editWorkOrder(item) {
      this.proWorkAllVo = {};
      this.editDialog = true;
      getWorkOrderDetail(item.pkProWork).then((res) => {
        res.data.proWorkCrafts.forEach((key1) => {
          key1.userIds = [];
          key1.newUserIds = [];
          key1.allUserList = JSON.parse(JSON.stringify(this.staffList)); // 必须深拷贝，不会影响原数组
          if (key1.proWorkCraftUsers) {
            key1.proWorkCraftUsers.forEach((key2) => {
              key1.userIds.push(key2.userId);
              key1.allUserList.forEach((key3, index) => {
                if (key2.userId == key3.userId) {
                  key1.allUserList.splice(index, 1);
                }
              });
            });
          }
        });
        res.data.proWorkCrafts = res.data.proWorkCrafts.sort(
          (a, b) => Number(a.craftOrder) - Number(b.craftOrder)
        );
        this.proWorkAllVo = res.data;
        // console.log(this.proWorkAllVo);
        this.showSkeleton = false;
      });
    },
    // 确定修改
    confirmEdit() {
      this.proWorkAllVo.proWorkCrafts.forEach((ppKey) => {
        ppKey.proWorkCraftUsers = [];
        ppKey.newUserIds.forEach((userKey) => {
          ppKey.allUserList.forEach((staffKey) => {
            if (userKey == staffKey.userId) {
              let staffItem = {
                pkCraftInfo: ppKey.pkCraftInfo,
                userId: staffKey.userId,
              };
              ppKey.proWorkCraftUsers.push(staffItem);
            }
          });
        });
      });
      // console.log(this.proWorkAllVo);
      addWorkOrder(this.proWorkAllVo).then((res) => {
        console.log(res);
        this.$message.success("修改成功");
        this.getHistoryWorkOrderList();
        this.editDialog = false;
      });
    },
    // 删除工单
    delWorkOrder(item) {
      this.$confirm(
        "此操作将永久删除当前工单信息及相关报工信息，是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delWorkOrder(item.pkProWork).then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.getHistoryWorkOrderList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 结束工单
    endWorkOrder(item) {
      this.$confirm("是否设置当前工单的状态为“结束”?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          endWorkOrder(item.pkProWork).then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.getHistoryWorkOrderList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },

    //分页修改每页显示条数
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.getHistoryWorkOrderList();
    },
    //分页跳转页面
    handleCurrentChange(val) {
      this.queryForm.pageNum = val;
      this.getHistoryWorkOrderList();
    },
  },
};
</script>

<style>
.row-bg {
  padding: 10px 0;
}

.popover-content {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 3px;
}

.el-button--mini.is-circle {
  padding: 2px !important;
}
.el-form-item {
  margin-bottom: 0px;
}
.form-container {
  flex-wrap: wrap;
  display: block;
  display: flex;
  align-items: center;
}
</style>
